﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using Casamiel.Domain;
using Casamiel.Common;
using System.Net.Http;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Application;
using Newtonsoft.Json.Linq;
using Casamiel.Common.Extensions;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetTicketCodeByIdCommandHandler:BaseCommandHandler,IRequestHandler<GetTicketCodeByIdCommand,BaseResult<string>>
	{
		private readonly IMemberService _memberService;
		private readonly IMemberCouponRepository _memberCouponRepository;
		public GetTicketCodeByIdCommandHandler(IMemberService  memberService, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)

		{
			_memberService = memberService ;
			_memberCouponRepository = memberCouponRepositor;
		}

		public async Task<BaseResult<string>> Handle(GetTicketCodeByIdCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var member =await _memberService.FindAsync<ICasaMielSession>(request.Mobile,true).ConfigureAwait(false);
			if (member == null) {
				return new BaseResult<string>("", 9999, "会员不存在");
			}
			var coupon = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(request.MCID).ConfigureAwait(false);
			if (coupon == null || coupon.MID!=member.ID) {
				return new BaseResult<string>("", 9999, "券不存在");
			}

			var IcRsp = await NetICService.Tmticketquery(new Domain.Request.IC.TmticketqueryReq { ticketcode = coupon.Ticketcode }).ConfigureAwait(false);
			if (IcRsp.code == 0) {
				var j = JObject.Parse(IcRsp.content);
				var state = j["state"].ToInt16(0);
				switch (state) {
					case 3:
						return new BaseResult<string>(coupon.Ticketcode, IcRsp.code, IcRsp.msg);
					case 0:
						if (coupon.State != 0) {
							coupon.State = 0;
							await _memberCouponRepository.UpdateAsync<ICasaMielSession>(coupon).ConfigureAwait(false);
						}
						
						return new BaseResult<string>("",9999, "已使用");
					case -2:
						if (coupon.State != -2) {
							coupon.State = -2;
							await _memberCouponRepository.UpdateAsync<ICasaMielSession>(coupon).ConfigureAwait(false);
						}
						return new BaseResult<string>("", 9999, "已销毁");
					case -1:
						if (coupon.State != -1) {
							coupon.State = -1;
							await _memberCouponRepository.UpdateAsync<ICasaMielSession>(coupon).ConfigureAwait(false);
						}
						return new BaseResult<string>("", 9999, "券不可用");
				}

			}

			return new BaseResult<string>("", IcRsp.code, IcRsp.msg);
		}
	}
}
